const express = require('express');
//引入连接池模块
const pool = require('../util/pool.js');
// 引入工具模块
const selfFun = require('../util/selfFun.js');
const myfs = require("fs");
//创建路由器对象
const r = express.Router();
let pho = /^1[3-9]\d{9}$/;
//1.用户注册(post /reg)

r.post('/reg', (req, res, next) => {
  //1.1获取流传递的数据
  let obj = req.body;
  //1.2验证各项数据是否为空
  let isnull = selfFun.isNull(obj);
  if (isnull !== 'no') {
    res.send(isnull);
    return;
  }
  console.log(obj);

  /*   if (!pho.test(obj.phone)) {
      res.send({ code: 405, msg: 'phone格式不对！' });
      return;
    } */
  //1.3执行SQL命令
  pool.query('insert into xz_user set ?', [obj], (err, result) => {
    if (err) {
      //把错误交给下一个中间件
      next(err);
      //阻止往后执行
      return;
    }
    // console.log(result);
    //执行成功
    res.send({
      code: 200,
      msg: '注册成功'
    });
  });
});
//2.用户登录

// 用户登录的路由
r.post('/login', (req, res, next) => {
  let obj = req.body;
  // console.log(obj);
  if (!obj.uname) {
    res.send({
      code: 401,
      msg: '用户名不能为空!'
    });
    // console.log(obj.uname);
    return;
  } else if (!obj.upwd) {
    res.send({
      code: 401,
      msg: '密码不能为空!'
    });
    return;
  }
  pool.query('select * from xz_user where uname=? and upwd=?', [obj.uname, obj.upwd],
    (err, results) => {
      // console.log('results: ', results);
      if (err) {
        //把错误交给下一个中间件
        next(err);
        //阻止往后执行
        return;
      }
      if (results.length === 0) {
        res.send({
          code: 401,
          msg: '用户或密码错误！'
        });
        return;
      } else
        res.send({
          code: 200,
          msg: '登录成功！'
        });
    });
});
//修改用户
http: //127.0.0.1:8080/v1/users/update1
  r.put('/update:uid', (req, res, next) => {
    let obj = req.body;
    let uid = req.params.uid;
    let isnull = selfFun.isNull(obj);
    // 循环验证
    if (isnull !== 'no') {
      res.send(isnull);
      return;
    }
    pool.query('update xz_user set ? where uid=?', [obj, uid], (err, results) => {
      if (err) {
        next(err);
        return;
      }
      if (results.changedRows === 0) {
        res.send({
          code: 201,
          msg: '修改失败！'
        });
        return;
      }
      res.send({
        code: 200,
        msg: '修改成功'
      });
    });
  });
//删除指定用户信息
r.delete('/delete:uid', (req, res, next) => {
  let id = req.params.uid;
  pool.query('delete from xz_user where uid=?', [id], (err, results) => {
    console.log(results);
    if (err) {
      next(err);
      return;
    }
    if (results.affectedRows === 0) {
      res.send({
        code: 404,
        msg: '删除失败'
      });
      return;
    } else {
      res.send({
        code: 200,
        msg: '删除成功'
      });
    }
  });
});
// 查询指定用户信息
r.get('/fuser:uid', (req, res, next) => {
  let uid = req.params.uid;
  pool.query('select * from xz_user where uid=?', [uid], (err, results) => {
    if (err) {
      next(err);
      return;
    }
    if (results.length === 0) {
      res.send({
        code: 404,
        msg: '查询失败'
      });
      return;
    }
    // res.send({ code: 200, msg: '查询成功  ' });
    res.send(results);
  });
});
// 
r.get('/find', (req, res, next) => {
  let uid = req.query.uid;
  pool.query('select * from xz_user where uid=?', [uid], (err, results) => {
    if (err) {
      next(err);
      return;
    }
    if (results.length === 0) {
      res.send({
        code: 404,
        msg: '查询失败'
      });
      return;
    }
    // res.send({ code: 200, msg: '查询成功  ' });
    res.send(results);
  });
});
//f分页查询
//2
r.get('/list', (req, res, next) => {
  let obj = req.query;
  // console.log(obj);
  let page = parseInt(obj.page);
  let num = parseInt(obj.num);
  if (!obj.num) num = 5;
  if (!obj.page) page = 0;
  page = (page - 1) * num;

  pool.query('select * from xz_user limit ?,?', [page, num], (err, results) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(results);
    if (results.length === 0) {
      res.send({
        code: 404,
        msg: '查询失败'
      });
      return;
    }
    // 
    res.send(results);
  });

});

// 查询所有用户
r.get('/list2', (req, res, next) => {
  pool.query('select * from xz_user', (err, results) => {
    if (err) {
      next(err);
      return;
    }
    // console.log(results);
    if (results.length === 0) {
      res.send({
        code: 404,
        msg: '查询失败'
      });
      return;
    }
    // 
    res.send(results);
  });

});

//上传用户头像
r.post("/upimg", (req, res, next) => {
  /* console.log(req.files); //文件上传请求信息
  console.log(req.query.uid); */
  let tempPath = req.files[0].path; //找到临时路径
  var obj = req.files[0].fieldname;
  let uid = req.query.uid;
  if (!uid) {
    res.send({
      code: 201,
      msg: '修改失败！'
    });
    return;
  }
  // selfFun.getSuffix(obj)得到上传文件后缀
  // console.log('selfFun.getSuffix(obj): ', selfFun.getSuffix(obj));
  let filename = "user" + uid + '.' + selfFun.getSuffix(obj);
  let targetPath = "views/imgStoreHouse/avatar/" + filename; //将文件放入上传上来的目标路径
  console.log('targetPath: ', targetPath);
  if (myfs.existsSync("./views/imgStoreHouse/avatar/") == false) { //判断upload路径下是否存在该用户的文件夹
    myfs.mkdirSync("./views/imgStoreHouse/avatar/"); //没有的话，就创建一个文件夹
  }
  let src="imgStoreHouse/avatar/"+filename;
  myfs.rename(tempPath, targetPath, function (err, data) {
    if (err) {
      next(err);
      return;
    }
    // 检查文件是否上传成功
    if (!myfs.existsSync(targetPath)) {
      res.send({
        code: 201,
        msg: '上传失败！'
      });
      return;
    }
    // 上传成功后向数据库中存入文件路径
    pool.query('update xz_user set avatar=? where uid=?', [src, uid], (err, results) => {
      if (err) {
        next(err);
        return;
      }
      if (results.affectedRows) {
        res.send({
          code: 200,
          msg: '上传成功！'
        });
      }
    });
  });
});
//导出路由器对象
module.exports = r;